/*
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  Author: g0tsu
 *  Email:  g0tsu at dnmx.0rg
 */

#include <stdio.h>
#include <config.h>
#include <libhighlight.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>

enum {
  PRINT_TYPE_TERM,
  PRINT_TYPE_HTML
};

#ifdef CONFIG_USE_HTML
static char * print_html(hl_root *root) {
  return hl_compile_html(root);
}
#endif

static char * print_term(hl_root *root) {
  return hl_compile_term(root);
}

static void usage(char *prog) {
  fprintf(stdout, "Usage: %s <input file>\n", prog);
  fprintf(stdout, "\t-v\t\tversion information\n");
  fprintf(stdout, "\t-h\t\tthis help\n");
#ifdef CONFIG_USE_HTML
  fprintf(stdout, "\t-t\t\thtml output\n");
#endif
  exit(1);
}

int main(int ac, char **av) {
  int fd;
  struct stat fdstat;
  int ptype = PRINT_TYPE_TERM;
  char *filename = NULL;
  char *out;
  int opt;
  hl_root *root;
  char useopt = 0;

  while ((opt = getopt(ac, av, "vth")) != -1) {
    switch (opt) {
      case 'v':
        fprintf(stdout, "%s %s\n", av[0], VERSION);
        exit(0);
        break;
      case 'h':
        usage(av[0]);
        break;
#ifdef CONFIG_USE_HTML
      case 't':
        ptype = PRINT_TYPE_HTML;
        useopt++;
        break;
#endif
      default:
        break;
    }
  }

  if (ac > (1 + useopt)) {
    filename = strdup(av[ac - 1]);

    if (stat(filename, &fdstat) !=0 || (fdstat.st_mode & S_IFMT) != S_IFREG) {
      fprintf(stderr, "The %s is not a \"regular\" file\n", filename);
      return ENOENT;
    }

    if ((fd = open(filename, O_RDONLY)) < 0) {
      perror("open()");
      return ENOENT;
    }
  } else {
    fd = fileno(stdin);
  }

  if (!(root = hl_parser_file(fd, NULL))) {
    fprintf(stderr, "Unable to parse file\n");
    return ENOENT;
  }

  if (filename) {
    close(fd);
    free(filename);
  }

  if (ptype == PRINT_TYPE_HTML)
    out = print_html(root);
  else
    out = print_term(root);

  if (!out) {
    fprintf(stderr, "Unable to compile output\n");
    return EILSEQ;
  }

  hl_root_free(root);

  puts(out);
  free(out);

  return 0;
}

